<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['alarm:alarmConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['alarm:alarmConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['alarm:alarmConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['alarm:alarmConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="优先级" align="center" prop="priority" />
      <el-table-column label="监听变量" align="center" prop="monitorEvents" />
      <el-table-column label="报警条件" align="center" prop="expression" />
      <el-table-column label="通知方式" align="center" prop="alarmModel" width="300">
          <template slot-scope="scope">
            <el-checkbox
              v-for="dict in dict.type.notify_model"
              :key="dict.value"
              :label="parseInt(dict.value)"
              :checked="displayChecked(dict.value,scope.row)"
              :disabled="true"
            >{{dict.label}}</el-checkbox>
          </template>
      </el-table-column>
      <el-table-column label="告警联动设备" align="center" prop="linkageDevicesName" />
      <el-table-column label="告警文本" align="center" prop="alarmContent" />
      <el-table-column label="是否有效" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['alarm:alarmConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['alarm:alarmConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备报警配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="1" :max="10" label="请输入优先级"></el-input-number>
        </el-form-item>
        <el-form-item label="监听场地" prop="siteId">
          <el-select v-model="form.siteId" placeholder="请选择监听场地">
            <el-option v-for="item in sites" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监听变量" prop="priority">
          <el-select v-model="form.deviceDefinedId" placeholder="请选择设备" @change="getDeviceEvents">
            <el-option v-for="item in deviceDefines" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>

          <el-select v-model="form.eventId" placeholder="请选择变量" style="margin-left:30px;">
            <el-option v-for="item in deviceEvents" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="报警条件" prop="expression">
          <el-input v-model="form.expression" placeholder="请输入报警条件" />
        </el-form-item>
        <el-form-item label="告警方式" prop="alarmModel">
          <el-checkbox-group v-model="alarmModel">
            <el-checkbox
              v-for="dict in dict.type.notify_model"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="报警联动" prop="alarmModel">
          <el-table v-loading="loading" :data="[{deviceName:'测试摄像头',eventName:'抓拍',eventParams:''}]">
            <el-table-column label="设备名称" align="center" prop="deviceName" />
            <el-table-column label="执行事件" align="center" prop="eventName" />
            <el-table-column label="事件参数" align="center" prop="eventParams" />
          </el-table>
        </el-form-item> -->
        <el-form-item label="报警联动设备" prop="linkageDevices">
          <div><el-tag type="success">{{form.linkageDevicesName}}</el-tag></div>
          <el-button @click="openSelectDevice" type="info">选择设备</el-button>
        </el-form-item>
        <el-form-item label="告警文本" prop="alarmContent">
          <el-input type="textarea" v-model="form.alarmContent" placeholder="请输入告警文本" />
        </el-form-item>
        <el-form-item label="是否有效">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <select-device ref="selectDevice" @selectDone="handleSelectDevice"></select-device>
  </div>
</template>

<script>
import { listAlarmConfig, getAlarmConfig, delAlarmConfig, addAlarmConfig, updateAlarmConfig } from "@/api/alarm/alarmConfig";
import { optionSites } from "@/api/site/site";
import selectDevice from "./selectDevice";
import { optionDefineds } from "@/api/ztIot/defined";
import { optionEvents } from "@/api/alarm/deviceEvent";
export default {
  name: "AlarmConfig",
  dicts: ['common_status','notify_model'],
  components: { selectDevice },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备报警配置表格数据
      alarmConfigList: [],
      alarmModel:[],
      deviceDefines:[],
      deviceEvents:[],
      sites:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        expression: null,
        alarmModel: null,
        linkageDevices: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        eventId: [
          { required: true, message: "配置参数Id不能为空", trigger: "blur" }
        ],
        expression: [
          { required: true, message: "报警条件不能为空", trigger: "blur" }
        ],
        alarmModel: [
          { required: true, message: "告警方式", trigger: "blur" }
        ],
        state: [
          { required: true, message: "是否有效不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeviceDefines();
    this.getSites();
  },
  methods: {
    /** 查询设备报警配置列表 */
    getList() {
      this.loading = true;
      listAlarmConfig(this.queryParams).then(response => {
        this.alarmConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDeviceDefines(){
      optionDefineds().then(res => {
        this.deviceDefines = res.data
      })
    },
    //查询设备变量
    getDeviceEvents(_definedId){
      this.deviceEvents = []
      optionEvents({definedId:_definedId,type:'01'}).then( res => this.deviceEvents = res.data)
    },
    getSites(){
      optionSites().then( res => this.sites = res.data)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.alarmModel = []
      this.form = {
        id: null,
        name: null,
        priority:1,
        deviceDefinedId:null,
        siteId:null,
        eventId: null,
        expression: null,
        alarmModel: null,
        linkageDevices: null,
        state: 1,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备报警配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAlarmConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.alarmModel = response.data.alarmModel.split(',');
        this.getDeviceEvents(this.form.deviceDefinedId)
        this.title = "修改设备报警配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.alarmModel && this.alarmModel.length>0){
        this.form.alarmModel = this.alarmModel.join(',')
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAlarmConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlarmConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备报警配置编号为"' + ids + '"的数据项？').then(function() {
        return delAlarmConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('alarm/alarmConfig/export', {
        ...this.queryParams
      }, `alarmConfig_${new Date().getTime()}.xlsx`)
    },
    displayChecked(checkValue , row){
      return row.alarmModel.indexOf(checkValue) >= 0
    },
    openSelectDevice() {
      this.$refs.selectDevice.show();
    },
    handleSelectDevice(data) {
      this.form.linkageDevices = data.id
      this.form.linkageDevicesName = data.name
    },
  }
};
</script>
